#include<iostream>
#include<string>
using namespace std;
typedef struct node{
    int data;
    struct node* next;
}Node;
class Stack{
    public:
    int length;// 栈中的元素个数
    struct node* head;
    Stack();// 构造函数
    void clearStack();
    int isempty();
    int getLength();
    int getTop();
    void push(int data);
    int popStack();
};
int main(){
    Stack stack;
    stack.push(1);
    stack.push(2);
    stack.push(3);
    stack.push(4);
    stack.push(5);
    cout<<"栈顶元素"<<stack.getTop()<<endl;
    for(int i=0;i<stack.length;i++){
        cout<<stack.popStack()<<" ";
    }
    cout<<stack.popStack()<<" ";
    cout<<stack.popStack()<<" ";
    cout<<stack.popStack()<<" ";
    

}
Stack::Stack(){
    this->head=(Node*)malloc(sizeof(Node));
    this->head->data=0;
    this->head->next=NULL;
    this->length=this->head->data;
}
void Stack::clearStack(){
    this->head->data=0;
    this->head->next=NULL;
    this->length=0;
}
int Stack::isempty(){
    if(this->head->data==0){
        return 1;
    }
        return 0;
}
int Stack::getLength(){
    return this->length;
}
int Stack::getTop(){
    if(this->length==0){
        cout<<"栈空"<<endl;
        return -1;
    }
    else{
        return this->head->next->data;// 注意头指针指向栈的最上方一个元素的上方
    }
}
void Stack::push(int data){
        head->data++;
        this->length++;
        Node* pnew=(Node*)malloc(sizeof(Node));
        pnew->data=data;
        pnew->next=head->next;
        head->next=pnew;
}
int Stack::popStack(){
    if(this->isempty()==1){
        cout<<"栈空,弹栈失败"<<endl;
        return -1;
    }
    else{
        head->data--;
        this->length--;
        Node* temp=head->next;
        head->next=temp->next;
        return temp->data;
    }
}